package io.github.zerobyteword.oneasynctool;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class OneAsyncTool {

    public static boolean runAsyncTask(ExecutorService executorService, int timeOut, WorkNode<?>... workNodes) throws InterruptedException, TimeoutException {
        if (workNodes == null || workNodes.length == 0) {
            return false;
        }
        int len = workNodes.length;
        CountDownLatch countDownLatch = new CountDownLatch(len);
        for (WorkNode<?> workNode : workNodes) {
            workNode.configRunInfo(executorService, countDownLatch);
        }
        for (int i = 0; i < len; i++) {
            if (workNodes[i].dependIsEmpty()) {
                workNodes[i].submitNewTask();
            }
        }
       boolean result =   countDownLatch.await(timeOut, TimeUnit.MILLISECONDS);
        if (!result || countDownLatch.getCount() > 0) {
            for (WorkNode<?> workNode : workNodes) {
                workNode.cancel();
            }
            return false;
        }
        return true;
    }
}
